/**
 * Copyright (C) 2007-2011 JUG Events Team <info@jugevents.org>
 *
 * This file is part of JUG Events Web Application.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package it.jugpadova.blol;


import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.velocity.app.VelocityEngine;
import org.jugevents.core.Conf;
import org.jugevents.core.dao.JuggerDao;
import org.jugevents.core.po.Event;
import org.jugevents.core.po.JUG;
import org.jugevents.core.po.Jugger;
import org.parancoe.plugins.securityevolution.Group;
import org.parancoe.plugins.securityevolution.User;
import org.parancoe.plugins.securityevolution.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;

/**
 * General purpose BO services. The methods defined in this
 * class should be called only by the others BO.
 *
 * @author Enrico Giurin
 *
 */
@Component("servicesBo")
public class ServicesBo {

    /**
     * min value for threshold access.
     */
    public static final double MIN_THRESHOLD_ACCESS = 0d;
    /**
     * Max value for threshold access
     */
    public static final double MAX_THRESHOLD_ACCESS = 1d;
    /**
     * Template for the email on updating KML
     */
    public static final String KML_UPDATE_EMAIL_TEMPLATE =
            "it/jugpadova/kmlUpdateEmailTemplate.vm";
    private static final Logger logger = LoggerFactory.getLogger(ServicesBo.class);
    @Resource
    private JuggerDao juggerDao;
   
    @Resource
    private UserDao userDao;
    @Resource
    private VelocityEngine velocityEngine;
    @Resource
    private JavaMailSender mailSender;
    @Resource
    private Conf conf;

   
    /**
     * Send an email with the upadted kml data and fragment.
     *
     * @param jugger The jugger that did the update
     * @param jug The updated JUG
     * @param isNewJug True if it's a new JUG
     */
    public void sendUpdatedKmlDataEmail(final Jugger jugger, final JUG jug,
            final boolean isNewJug, final String kmlPlacemark) {
        MimeMessagePreparator preparator = new MimeMessagePreparator() {

            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo(conf.getKmlUpdateToAddress());
                message.setFrom(conf.getKmlUpdateFromAddress());
                message.setReplyTo(conf.getKmlUpdateReplyAddress());
                if (isNewJug) {
                    message.setSubject(conf.getKmlUpdateSubjectPrefix() + "The \"" + jug.getName()
                            + "\" has been added");
                } else {
                    message.setSubject(conf.getKmlUpdateSubjectPrefix() + "The \"" + jug.getName()
                            + "\" has been updated");
                }
                Map model = new HashMap();
                model.put("jug", jug);
                model.put("jugeventsBaseUrl", conf.getJugeventsBaseUrl());
                model.put("jugEventsEmailLogoUrl", conf.getJugeventsBaseUrl()
                        + "/images/jugeventsLogoReflectedWhite.jpg");
                model.put("jugger", jugger);
                model.put("kmlPlacemark", StringEscapeUtils.escapeHtml(
                        kmlPlacemark));
                String text = VelocityEngineUtils.mergeTemplateIntoString(
                        velocityEngine, KML_UPDATE_EMAIL_TEMPLATE, model);
                message.setText(text, true);
            }
        };
        this.mailSender.send(preparator);
        logger.info("Sent updated kml email for \"" + jug.getName() + "\" to " + conf.
                getKmlUpdateToAddress() + " from " + conf.getKmlUpdateFromAddress());
    }

    private void sendEmail(final Jugger jugger, final String baseUrl,
            final String subject, final String template, final String sender,
            final String mailTo, final String motivation) {
        MimeMessagePreparator preparator = new MimeMessagePreparator() {

            @SuppressWarnings(value = "unchecked")
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo(mailTo);
                message.setFrom(sender);
                message.setSubject(subject);
                Map model = new HashMap();
                model.put("jugger", jugger);
                model.put("baseUrl", baseUrl);
                model.put("motivation", motivation);

                model.put("username", URLEncoder.encode(jugger.getUser().
                        getUsername(), "UTF-8"));
                String text = VelocityEngineUtils.mergeTemplateIntoString(
                        velocityEngine, template, model);
                message.setText(text, true);
            }
        };
        this.mailSender.send(preparator);
    }

    private void sendAdminEmail(final Jugger jugger, final String baseUrl,
            final String subject, final String template, final String sender,
            final String mailTo) {
        MimeMessagePreparator preparator = new MimeMessagePreparator() {

            @SuppressWarnings(value = "unchecked")
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo(mailTo);
                message.setFrom(sender);
                message.setSubject(subject);
                Map model = new HashMap();
                model.put("jugger", jugger);
                model.put("baseUrl", baseUrl);
               
                String text = VelocityEngineUtils.mergeTemplateIntoString(
                        velocityEngine, template, model);
                message.setText(text, true);
            }
        };
        this.mailSender.send(preparator);
    }

    /**
     * Retrieves the current authenticated user.
     * @return
     */
    public String getCurrentUser() {        
        return authenticatedUsername();        
    }

    /**
     * Returns the current jugger, that is the jugger associated with the current authenticated user.
     * If no jugger is found returns null
     * @return
     */
    public Jugger getCurrentJugger() {
        String currentUser = getCurrentUser();        
        Jugger currentJugger = juggerDao.searchByUsername(currentUser);
            if (currentJugger == null) {
            	logger.warn("No jugger found with the '" + currentUser + "' username");
            }        
        return currentJugger;
    }

    /**
     * This method return true in one of these two cases:
     * <ol>
     *  <li>The user identified by username is the authentified user</li>
     *  <li>The authentified user is in the role of ROLE_ADMIN</li>
     *  </ol>
     * @param username
     */
    public boolean checkAuthorization(String username) {
        String name = authenticatedUsername();
        if (name != null) {
            if (username.equals(name)) {
                return true;
            }
        } // end of if
        // is the authenticated user in the role_admin?

       
        return isAdmin(getCurrentUser());

    } // end of method

    public boolean isCurrentUserAuthorized(User user) {
        return checkAuthorization(user.getUsername());
    }

    /**
     * Returns true if the user is in the role of ROLE_AMIN.
     * @param user
     * @return
     */
    public boolean isAdmin(String username) {    	
    	User user = userDao.findByUsername(username);
    	//user is null if username is anonymousUser
    	if(user == null)
    		return false;
       
        for (Group group : user.getGroups()) {
            if ("administrator".equals(group.getName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * Returns the authenticated username.
     * @return
     */
    public String authenticatedUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return authentication.getName();
        }
        return null; //not so good...
    }

    /**
     * Check if the current user can manage an event.
     *
     * @param event The event to manage
     * @return true if the user can manage the event
     */
    public boolean canCurrentUserManageEvent(Event event) {
    	return true;
    	//TODO review this
    
       /* boolean result = false;
        String user = getCurrentUser();
        if(user.equals("anonymousUser"))
        	return false;
        if (user != null) {
            if (isAdmin(user)) {
                // admins, of course
                return true;
            }
            if (event.getJugOwner() != null) {
                if (event.getJugOwner().getUser().getUsername().equals(
                        user)) {
                    // the event jugOwner
                    return true;
                }
                Jugger currentJugger = getCurrentJugger();
                
            }
        }
        return result;
    */}
}
